<template>
    <a-modal :title="formRelation.title" :width="600" :visible="formRelation.visible" :maskClosable="false" :footer="null" @cancel="close">
      <a-form-model :model="codeForm" :label-col="{ span: 5 }"
    :wrapper-col="{ span: 18 }" ref="codeForm">
        <a-card :bordered="false">
          <a-alert :message="modMessage" type="info" closable/>
          <a-form-model-item label="审核状态">
            <a-radio-group v-model:value="codeForm.state" @change="radioChange" name="radioGroup">
              <a-radio value="1">通过</a-radio>
              <a-radio value="2">驳回</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="业务模式" v-if="modData.length >=1">
            <a-select v-model:value="codeForm.busMod" :disabled="dispath">
              <a-select-option v-for="role in modData" :key="role.busmod">
                  {{ role.modals }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="驳回理由">
                <a-input type="textarea" :disabled="!dispath" :rows="4" placeholder="驳回理由" v-model:value="codeForm.rejectReason" />
            </a-form-model-item>
        </a-card>
        <a-card :bordered="false" v-if="payChannel == 3 || payChannel == 4" style="border-top: 1px solid #e8e8e8;">
          <a-form-model-item label="动态口令手机号（支付宝）">
              <label>{{userDetail.dynamicWordPhone}}</label>
          </a-form-model-item>
          <a-form-model-item label="短信验证码">
            <a-input-group compact>
              <a-input v-model:value="codeForm.verifiedCode" style="width: calc(100% - 220px)" />
              <a-button :disabled="!canClick" @click="getVerificationCode" type="primary">{{ getCodeText }}</a-button>
            </a-input-group>
          </a-form-model-item>
        </a-card>
      </a-form-model>
          
      <div class="custom-drawer-footer">
        <a-popover title="温馨提示">
          <template #content>
            <p style="width: 250px;">驳回状态，请填写驳回理由，所有费用停止转账，数据回滚到驳回列表。确认提交后，等待银行审核</p>
            <p style="width: 250px;">通过状态，等待银行处理，可能有短暂延迟，数据回滚到结算成功列表</p>
          </template>
          <a-button type="link" style="float: left;" icon="question-circle">帮助</a-button>
        </a-popover>
        <a-button type="primary" :loading="submitLoading" @click="submitTaskBill">确认提交</a-button>
      </div>
    </a-modal>
</template>
<script>

import { mapGetters } from 'vuex'
import notification from 'ant-design-vue/es/notification'
import { 
    allSettlementSendCode,
    allSettlementVerifySuccess,
    allGetSettlementCmbMode,
    allSettlementReject
} from '@/api/manage/sttle'
export default {
  name: 'sttleBillApply',
  data () {
    return {
        formRelation:{
            title:'结算审核',
            visible:false,
        },
        codeForm:{
          state:'',
          verifiedCode:'',
          rejectReason:'',
          busMod:''
        },
        dispath:false,
        modData:[],
        modMessage:'',
        settleBatchCode:'',
        getCodeText:'获取验证码',
        canClick:true, 
        totalTime:60,
        clock:null,
        payChannel:'',
        submitLoading:false
    }
  },
  computed: {
    ...mapGetters(['userInfo','enterAccount','userDetail'])
  },
  methods:{
    add(item){
      let {codeForm} = this;
      for(var key in codeForm){
        codeForm[key] = '';
      }
      this.settleBatchCode = item.settleBatchCode;
      this.canClick = true;
      this.dispath = false;
      this.getCodeText = '获取验证码';
      this.totalTime = 60;
      window.clearInterval(this.clock)
      this.clock = null;
      this.modData =[];
      this.payChannel = item.payChannel;
      if(item.payChannel === 1){
        this.modMessage = '当前支付通道 招商银行';
        this.getCmbMode(item.taskId);
      }else{
        this.modMessage = item.payChannel === 3 ? '当前支付通道 支付宝到卡':'当前支付通道 支付宝到户';
        this.formRelation.visible = true;
      }
    },
    async getCmbMode(taskId){
      const {code,data} = await allGetSettlementCmbMode(taskId);
      if(code === '1'){
        if(data && typeof(data)=='string'){
          let dataObj = JSON.parse(data);
          if(dataObj.data == null){
      this.$error({
        width:460,
        okText:'关闭',
        content:(
          <div>
            <p class="msg-content">{dataObj.message}</p>
          </div>
        ),
        onOk() {},
      });

          }else{
            this.modData= JSON.parse(data).data;
            this.formRelation.visible = true;
          }
        }else{
          this.modData= data;
          this.formRelation.visible = true;
        }
      }
    },
    async getVerificationCode(){
        if(!this.settleBatchCode){
            return this.$message.error('结算批次未获取，重试或者联系管理员！');
        }
        let params = {settleBatchCode:this.settleBatchCode}
        const {code} = await allSettlementSendCode(params);
        if(code === '1'){
            this.verificationCode();
        }
    },
    radioChange(e){
      let {settleBatchCode,codeForm} = this;
      this.dispath = e.target.value === '1' ? false:true;
      if(this.dispath){
        codeForm.busMod ='';
      }else{
        codeForm.rejectReason ='';
      }
    },
    verificationCode() {
      if (!this.canClick) return  
      this.canClick = false
      this.getCodeText = this.totalTime + 's后重新发送'
      this.clock = window.setInterval(() => {
        this.totalTime--
        this.getCodeText = this.totalTime + 's后重新发送'
        if (this.totalTime < 0) {
          window.clearInterval(this.clock)
          this.getCodeText = '重新发送验证码'
          this.totalTime = 60
          this.canClick = true  
        }
      },1000)
    },
    async submitTaskBill(){
        let that = this;
        let {settleBatchCode,codeForm} = this;
        if(!codeForm.state){
          return this.$message.error('请选择审核状态！');
        }
        let params = {};
        params.state = codeForm.state;
        if(this.payChannel === 1 && codeForm.state === '1'){
          if(!codeForm.busMod){
            return this.$message.error('请选择业务模式！');
          }
          params.busMod = codeForm.busMod;
        }else if(this.payChannel === 3 || this.payChannel === 4 && codeForm.state === '1'){
          if(!codeForm.verifiedCode){
            return this.$message.error('请输入验证码');
          }
          params.verifiedCode= codeForm.verifiedCode;
        }
        params.settleBatchCode= settleBatchCode;
        if(codeForm.state === '1'){
          this.submitLoading = true;
          const {code,message} = await allSettlementVerifySuccess(params);
          this.submitLoading = false;
          if(code === '1'){
            this.$message.success('操作成功');
            this.formRelation.visible = false;
            window.clearInterval(this.clock)
            this.$emit("on-ok");
          }else if(code === '112'){
            this.$message.success(message);
            this.formRelation.visible = false;
            window.clearInterval(this.clock)
            this.$emit("on-ok");
          }
        }else if(codeForm.state === '2'){
          if(!codeForm.rejectReason){
            return this.$message.error('请填写驳回理由！');
          }
          this.$confirm({
            title: '温馨提示',
            content: '驳回后不能恢复，确定驳回',
            okText:'驳回',
            async onOk() {
              params.rejectReason = codeForm.rejectReason;
              return new Promise((resolve, reject) => {
                const res = that.confirmOnOk(resolve, reject, params)
                return res
              }).catch(() =>{})
            },
            onCancel() {},
          });
        }
    },
    async confirmOnOk(resolve, reject, params){
      const {code,message} = await allSettlementReject(params);
      if(code === '1'){
        resolve()
        this.$message.success('操作成功');
        this.formRelation.visible = false;
        window.clearInterval(this.clock);
        this.$emit("on-ok");
      }else if(code === '112'){
        resolve()
        this.$message.success(message);
        this.formRelation.visible = false;
        window.clearInterval(this.clock)
        this.$emit("on-ok");
      }
    },
    close(){
      const that = this;
      that.formRelation.visible = false;
    }
  }
}
</script>